var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var async = require('async');

var config = {
    userName: 'sa', // update me
    password: '1111', // update me
    server: '192.168.1.1',
    options: {
        instanceName: 'sql2008',
        database: 'TMS2017'
    }
}

function queryOrders() {
    return new Promise(function(resolve, reject) {
        var conn = new Connection(config);
        conn.on('connect', function(err) {
            if (err) {
                reject(err);
                return;
            }

            var orders = [];

            var request = new Request(
                'select top 10 * from OM_Order',
                function(err, rowCount, rows) {
                    conn.close();

                    if (err) {
                        reject(err);
                    } else {
                        resolve(orders);
                    }
                });

            request.on('row', function(columns) {
                var order = {}
                columns.forEach(function(column) {
                    order[column.metadata.colName] = column.value;
                });
                orders.push(order);
            });

            conn.execSql(request);
        });
    });
}

exports.getOrders = async function(req, res) {
    try {
        let orders = await queryOrders();
        res.json(orders);
    } catch (err) {
        console.log(err);
        res.json([]);
    }
    /*     let promise = queryOrders();
        promise
            .then(orders => res.json(orders))
            .catch(err => console.log(err)); */
}